/**
 * 
 */
package com.alstudio.view.viewpagerextend;

import java.util.ArrayList;

import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;

/**
 * @author alonso lee
 * 
 */
public class ALViewpagerCreator {

	private FixedTabsAdapter tabAdapter;
	private BaseViewPagerAdapter pagerAdapter;

	private ViewPager mViewPager;
	private FixedTabsView mFixedTabsView;

	private ViewPagerObserver viewPagerObserver;

	/**
	 * 
	 */
	public ALViewpagerCreator(LayoutInflater inflater,
			ArrayList<String> titles, ArrayList<View> views) {
		// TODO Auto-generated constructor stub
		viewPagerObserver = new ViewPagerObserver();
		initTabTitle(inflater, titles);
		initPagers(views);
	}

	/**
	 * 初始化title栏
	 * 
	 * @param inflater
	 * @param titles
	 */
	public void initTabTitle(LayoutInflater inflater, ArrayList<String> titles) {
		if (titles == null)
			return;
		tabAdapter = new FixedTabsAdapter(inflater, titles);
	}

	/**
	 * 初始化内容区
	 * 
	 * @param views
	 */
	public void initPagers(ArrayList<View> views) {
		pagerAdapter = new BaseViewPagerAdapter(views);
	}

	/**
	 * @return the mViewPager
	 */
	public ViewPager getViewPager() {
		return mViewPager;
	}

	/**
	 * @param mViewPager
	 *            the mViewPager to set
	 */
	public void setViewPager(ViewPager viewPager) {
		this.mViewPager = viewPager;
	}

	public void addOnPageChangeListener(OnPageChangeListener listener) {
		viewPagerObserver.addListener(listener);
	}

	/**
	 * @param mFixedTabsView
	 *            the mFixedTabsView to set
	 */
	public void setFixedTabsView(FixedTabsView fixedTabsView) {
		this.mFixedTabsView = fixedTabsView;
	}

	/**
	 * @return the mFixedTabsView
	 */
	public FixedTabsView getFixedTabsView() {
		return mFixedTabsView;
	}

	public void commit(int selectItem) {
		mViewPager.setAdapter(pagerAdapter);
		mViewPager.setOnPageChangeListener(viewPagerObserver);
		mViewPager.setCurrentItem(selectItem);
		mViewPager.setPageMargin(1);
		if (mFixedTabsView != null) {
			mFixedTabsView.setAdapter(tabAdapter);
			mFixedTabsView.setViewPager(mViewPager);
			viewPagerObserver.addListener(mFixedTabsView);
		}
	}

	public void commit() {
		mViewPager.setAdapter(pagerAdapter);
		mViewPager.setOnPageChangeListener(viewPagerObserver);
		mViewPager.setCurrentItem(0);
		mViewPager.setPageMargin(1);
		if (mFixedTabsView != null) {
			mFixedTabsView.setAdapter(tabAdapter);
			mFixedTabsView.setViewPager(mViewPager);
			viewPagerObserver.addListener(mFixedTabsView);
		}
	}

}
